const crypto = require('crypto');

const utils = require('./utils')

const {
	$_ULOG,
} = require('../logger/logger');

const interceptorConf = global.sysConfig.interceptor;

module.exports = function(req, res, next) {
	let path = req.path
		// let startReg = /^(\/images\/|\/css\/|\/build\/|\/js\/|\/xmstyle\/|\/ssstyle\/)/;
	let endReg = /(\.png|\.jpg|\.jpeg|\.gif|\.map|\.js|\.jsx|\.css|\.html)$/
	if (!endReg.test(path)) {
		$_ULOG.call(req, `===请求开始=[${path}]=interceptor.js=时间[${Date.now()}]==`)
	}
	/**
	 * 手机厂商接口 请求头md5验证
	 * 时间戳: timeStamp
	 * 校验码: identityCode === > (97 + md5(key + timeStamp))
	 * @param
	 * @return
	 */
	// if(interceptorConf.validate && (req.path in interceptorConf) && interceptorConf[req.path].validate){
	var pathIn = interceptorPath(req.path);
	if (interceptorConf.validate && pathIn && pathIn.validate) {
		var type = req[pathIn.type],
			identityCode = type[pathIn.enCode] || type[pathIn.enCode.toLowerCase()],
			md5 = crypto.createHash('md5'),
			accessToken = '',
			md5Args = '';
		for (var arg of pathIn.args) {
			md5Args += (type[arg] || type[arg.toLowerCase()]);
		}
		accessToken = pathIn.pre + md5.update(pathIn.key + md5Args).digest('hex');
		identityCode = identityCode && identityCode.toUpperCase();
		accessToken = accessToken && accessToken.toUpperCase();
		if (accessToken != identityCode) {
			res.type("json").send({
				status: "非法请求",
				statusCode: 500
			});
			return;
		}
	}
	next();
};

function interceptorPath(path) {
	// var _path = "/ultimate/" + path.split("/")[2],
	let pathArr = path.split("/")
	let _path = `/${pathArr[1]}/${pathArr[2]}`,
		channelPath = interceptorConf[_path];
	if (interceptorConf.channel_validate) {
		return channelPath;
	}
	if (path in interceptorConf) {
		if (typeof interceptorConf[path] == 'object') {
			if (path == _path) {
				return channelPath;
			}
			return utils.merge(channelPath, interceptorConf[path]);
			// return interceptorConf[path];
		}
		if (typeof interceptorConf[path] == 'string') {
			var valuePath = interceptorConf[path];
			// return arguments.callee(valuePath);
			return interceptorPath(valuePath);
		}
		return false;
	}
	return false;
}

// function pathValidate(req, pathIn){
// 	var type = req[pathIn.type],
// 		identityCode = type[pathIn.enCode] || type[pathIn.enCode.toLowerCase()],
// 		md5 = crypto.createHash('md5'),
// 		accessToken = '', md5Args = '';
// 	for(var arg of pathIn.args){
// 		md5Args += (type[arg] || type[arg.toLowerCase()]);
// 	}
// 	accessToken = pathIn.pre + md5.update(pathIn.key + md5Args).digest('hex');
// 	identityCode = identityCode && identityCode.toUpperCase();
// 	accessToken = accessToken && accessToken.toUpperCase();
// 	if(accessToken != identityCode){
// 		res.type("json").send({
// 			status: "非法请求",
// 			statusCode: 500
// 		});
// 		return;
// 	}
// }